<?php

Class Upload {

	private $_filename;
	private $_filesize;
	private $_filetype;
	private $_filecontent;
	private $_rootname;
	private $_dir;
	private $_id;
	
	//Drag and Drop Upload
	public function dadUpload($id, $filename, $content, $dir, $thumbs) {
		$this->_id = $id;
		$this->_dir = $dir;
		$this->_filename = $filename;
		$this->_filecontent = $content;
		$this->_filetype = end(explode('.', $this->_filename));
		if (!file_exists($this->_dir.$this->_id)) {
			mkdir($dir.$this->_id, 0777);
		}
		if ($this->checkType() == true && $this->checkSize() == true) {
			$i = 1;
			$this->_rootname = str_replace('.'.$this->_filetype, '', $this->_filename);
			while(file_exists($this->_dir.$this->_id.'/'.$this->_filename)) {
				$this->_filename = $this->_rootname.$i.'.'.$this->_filetype;
				$i++;
			}
			file_put_contents($this->_dir.$this->_id.'/'.$this->_filename, $this->_filecontent);
			//If $thumbs == true, create thumbnails from original image
			if ($thumbs == true) {
				$this->createThumbs();
			}
		}
	}
	
	public function initVar($dir, $filename) {
		$this->_dir = $dir;
		$this->_filename = $filename;
	}
	
	public function createThumbs() {
		//Create thumbnails
		$this->_filetype = end(explode('.', $this->_filename));
		$this->_rootname = str_replace('.'.$this->_filetype, '', $this->_filename);
		$filepath = $this->_dir.$this->_id.'/'.$this->_filename;
		$thumbs = unserialize(THUMBS);
		if (!file_exists($this->_dir.$this->_id.'/tb')) {
			mkdir($this->_dir.$this->_id.'/tb', 0777);
		}
		foreach($thumbs as $thumbsize) {
			$resizeObj = new Thumb($filepath);
			$resizeObj -> resizeImage($thumbsize, $thumbsize, 'auto');
			$resizeObj -> saveImage($this->_dir.$this->_id.'/tb/'.$this->_rootname.'-'.$thumbsize.'.'.$this->_filetype, 100);
		}
	}
	
	public static function deleteThumbs($imgtodel) {
		if(file_exists(str_replace(URL_ROOT, '', $imgtodel))){
			$img = str_replace(URL_ROOT, '', $imgtodel);
			$thumbs = unserialize(THUMBS);
			foreach($thumbs as $thumbsize) {
				$extension = end(explode('.', $img));
				$thumb = dirname($img).'/tb/'.basename(str_replace('.'.$extension, '', $img).'-'.$thumbsize.'.'.$extension);
				if (file_exists($thumb)) {
					unlink($thumb);
				}
			}
			unlink($img);
		}
		return "1";
	}
	
	//Check if file extension is in FILE_EXTENSION_AUTHORIZED array
	public function checkType() {
		if (in_array($this->_filetype, unserialize(FILE_EXTENSIONS_AUTHORIZED))) {
			return true;
		}
		else {
			return false;
		}
	}
	
	//Check if file size is not over MAX_FILE_SIZE
	public function checkSize() {
		if(filesize($this->_filecontent) <= MAX_FILE_SIZE) {
			return true;
		}
		else {
			return false;
		}
	}
	
}

?>